<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧部门树 -->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <!-- 右侧巡区管理区域 -->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="巡区名称" prop="areaName">
            <el-input
              v-model="queryParams.areaName"
              placeholder="请输入巡区名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="巡区类型" prop="areaType">
            <el-select
              v-model="queryParams.areaType"
              placeholder="巡区类型"
              clearable
              style="width: 240px"
            >
              <el-option label="常规区域" value="1" />
              <el-option label="重点区域" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增巡区</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="handleDraw"
            >绘图页面</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-user"
              size="mini"
              @click="handleAssignManage"
            >分配管理</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 巡区列表 -->
        <el-table
          v-loading="loading"
          :data="areaList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="巡区名称" align="center" prop="areaName" />
          <el-table-column label="巡区编号" align="center" prop="areaCode" />
          <el-table-column label="类型" align="center" prop="areaType">
            <template slot-scope="scope">
              <el-tag>{{ scope.row.areaType === 1 || scope.row.areaType === '1' ? '常规区域' : '重点区域' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="设置电子围栏" align="center">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.hasFence === 1 || scope.row.hasFence === true">是</el-tag>
              <el-tag type="info" v-else>否</el-tag>
            </template>
          </el-table-column>
        
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleModify(scope.row)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="mini" type="text" icon="el-icon-view" @click="handlePreview(scope.row)">查看</el-button>
              <el-button size="mini" type="text" icon="el-icon-user" @click="handleAssignUsers(scope.row)">分配用户</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 地图区域 -->
        <el-card class="box-card" style="margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>巡区地图</span>
          </div>
          <div class="map-container" ref="mapContainer"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/修改巡区对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="巡区名称" prop="areaName">
              <el-input v-model="form.areaName" placeholder="请输入巡区名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡区编号" prop="areaCode">
              <el-input v-model="form.areaCode" placeholder="请输入巡区编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择所属部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡区状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="巡区范围" prop="area">
              <div class="map-controls">
                <el-button type="primary" size="mini" @click="startDraw">开始绘制</el-button>
                <el-button type="warning" size="mini" @click="clearDraw">清除绘制</el-button>
                <el-button type="success" size="mini" @click="finishDraw">完成绘制</el-button>
                <el-button type="info" size="mini" @click="forceInitMap">重新初始化地图</el-button>
              </div>
              <div ref="dialogMapContainer" class="dialog-map-container"></div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户分配对话框 -->
    <el-dialog title="巡区用户分配" :visible.sync="assignDialogVisible" width="1000px" append-to-body>
      <div class="assign-container">
        <div class="assign-header">
          <h4>巡区：{{ currentArea.areaName }}</h4>
          <div class="assign-actions">
            <el-button type="primary" size="mini" @click="openSelectUser">添加用户</el-button>
            <el-button type="danger" size="mini" :disabled="selectedAssignIds.length === 0" @click="batchRemoveAssign">批量移除</el-button>
          </div>
        </div>
        
        <el-table
          v-loading="assignLoading"
          :data="assignedUsers"
          @selection-change="handleAssignSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="用户名称" align="center" prop="userName" />
      
          <el-table-column label="分配类型" align="center" prop="assignType">
            <template slot-scope="scope">
              <el-tag :type="scope.row.assignType === 1 ? 'primary' : 'success'">
                {{ scope.row.assignType === 1 ? '主要负责人' : '协助人员' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="分配时间" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="removeAssign(scope.row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 用户选择器 -->
    <select-user ref="selectUser" :areaId="currentArea.areaId" @select="handleUserSelect" />
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { listPatrolArea, getPatrolArea, addPatrolArea, updatePatrolArea, delPatrolArea } from '@/api/system/patrolArea';
import { getUsersByAreaId, batchAssignUsers, cancelUserAssign } from '@/api/system/patrolAreaUser';
import { deptTreeSelect } from '@/api/system/user';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import Pagination from "@/components/Pagination";
import SelectUser from './selectUser';

export default {
  name: 'PatrolArea',
  components: { Treeselect, Pagination, SelectUser },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 地图实例
      map: null,
      // 弹窗地图实例
      dialogMap: null,
      // 绘制工具
      mouseTool: null,
      // 弹窗绘制工具
      dialogMouseTool: null,
      // 当前绘制的覆盖物
      currentOverlay: null,
      // 部门树选项
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        areaName: undefined,
        areaType: undefined
      },
      // 表单参数
      form: {
        areaId: undefined,
        areaName: undefined,
        areaType: 1,
        hasFence: false,
        area: [],
        deptId: undefined
      },
      // 表单校验
      rules: {
        areaName: [
          { required: true, message: '巡区名称不能为空', trigger: 'blur' }
        ],
        areaType: [
          { required: true, message: '请选择巡区类型', trigger: 'change' }
        ],
        area: [
          { 
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error('请先绘制巡区范围'));
              } else if (value.length < 3) {
                callback(new Error('巡区范围至少需要3个点'));
              } else {
                callback();
              }
            }, 
            trigger: 'change' 
          }
        ]
      },
      // 巡区列表数据
      areaList: [],
      // 部门名称
      deptName: '',
      // 默认部门属性
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 是否显示搜索
      showSearch: true,
      // 用户分配相关
      assignDialogVisible: false,
      assignLoading: false,
      currentArea: {},
      assignedUsers: [],
      selectedAssignIds: []
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  watch: {
    open(newVal) {
      if (!newVal) {
        // 弹窗关闭时清理资源
        this.reset();
      }
    },
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
    if (this.dialogMap) {
      this.dialogMap.destroy();
    }
  },
  methods: {
    /** 查询巡区列表 */
    getList() {
      this.loading = true;
      listPatrolArea(this.queryParams).then(response => {
        this.areaList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 重新加载地图上的巡区
        this.loadAreas();
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 格式化部门树数据
    normalizer(node) {
      return {
        id: node.id,
        label: node.label,
        children: node.children
      };
    },
    async initMap() {
      try {
        const AMap = await AMapLoader.load({
          key: '4b98d24146ee2f4b43cc046b7886cb71',
          version: '2.0',
          plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.MouseTool', 'AMap.PolyEditor']
        });

        // 创建地图实例
        this.map = new AMap.Map(this.$refs.mapContainer, {
          zoom: 12,
          center: [114.085947, 22.547],
          viewMode: '3D'
        });

        // 添加地图控件
        this.map.addControl(new AMap.ToolBar());
        this.map.addControl(new AMap.Scale());

        // 初始化鼠标工具
        this.mouseTool = new AMap.MouseTool(this.map);
        
        // 加载已有巡区
        this.loadAreas();
      } catch (e) {
        console.error('地图加载失败', e);
      }
    },
    // 初始化弹窗地图
    async initDialogMap() {
      try {
        // 等待DOM完全渲染
        await this.$nextTick();
        
        // 确保容器存在
        if (!this.$refs.dialogMapContainer) {
          console.error('弹窗地图容器不存在');
          return Promise.reject('地图容器不存在');
        }
        
        // 使用MutationObserver监听容器尺寸变化
        const container = this.$refs.dialogMapContainer;
        await this.waitForContainerSize(container);
        
        const AMap = await AMapLoader.load({
          key: '4b98d24146ee2f4b43cc046b7886cb71',
          version: '2.0',
          plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.MouseTool', 'AMap.PolyEditor']
        });

        // 再次检查容器尺寸
        const rect = container.getBoundingClientRect();
        console.log('最终地图容器尺寸:', rect.width, 'x', rect.height);
        
        if (rect.width === 0 || rect.height === 0) {
          throw new Error('地图容器尺寸仍然为0');
        }

        // 创建弹窗地图实例
        this.dialogMap = new AMap.Map(container, {
          zoom: 12,
          center: [114.085947, 22.547],
          viewMode: '3D'
        });

        // 添加地图控件
        this.dialogMap.addControl(new AMap.ToolBar());
        this.dialogMap.addControl(new AMap.Scale());

        // 初始化弹窗鼠标工具
        this.dialogMouseTool = new AMap.MouseTool(this.dialogMap);
        
        // 监听绘制完成事件
        this.dialogMouseTool.on('draw', (event) => {
          this.currentOverlay = event.obj;
          this.$message.success('绘制完成，可以点击"完成绘制"确认');
        });
        
        console.log('弹窗地图初始化成功');
        return Promise.resolve();
      } catch (e) {
        console.error('弹窗地图加载失败', e);
        return Promise.reject(e);
      }
    },
    // 等待容器尺寸计算完成
    waitForContainerSize(container) {
      return new Promise((resolve, reject) => {
        let attempts = 0;
        const maxAttempts = 80; // 最多等待8秒
        
        const checkSize = () => {
          const rect = container.getBoundingClientRect();
          console.log(`检查容器尺寸 (${attempts + 1}/${maxAttempts}):`, rect.width, 'x', rect.height);
          
          if (rect.width > 0 && rect.height > 0) {
            console.log('容器尺寸计算完成');
            resolve();
            return;
          }
          
          attempts++;
          if (attempts >= maxAttempts) {
            reject(new Error('容器尺寸计算超时'));
            return;
          }
          
          setTimeout(checkSize, 100);
        };
        
        checkSize();
      });
    },
    // 加载巡区到地图上
    loadAreas() {
      if (!this.map) return;
      
      // 清除现有覆盖物
      this.map.clearMap();
      
      this.areaList.forEach(area => {
        if (area.area && area.area.length > 0) {
          // 确保area是数组格式
          let path = area.area;
          if (typeof area.area === 'string') {
            try {
              path = JSON.parse(area.area);
            } catch (e) {
              console.error('巡区坐标数据格式错误:', area.area);
              return;
            }
          }
          
          // 验证坐标数据
          if (!this.validateCoordinates(path)) {
            console.warn('巡区坐标数据无效:', area.areaName, path);
            return;
          }
          
          const polygon = new AMap.Polygon({
            path: path,
            strokeColor: '#FF33FF',
            strokeWeight: 2,
            strokeOpacity: 0.9,
            fillColor: '#1791fc',
            fillOpacity: 0.3,
            extData: area
          });
          
          polygon.on('click', () => {
            this.handlePreview(area);
          });
          
          this.map.add(polygon);
        }
      });
    },
    // 开始绘制
    startDraw() {
      if (!this.dialogMap || !this.dialogMouseTool) {
        this.$message.warning('地图未初始化，请稍后重试');
        return;
      }
      
      this.clearDraw();
      this.dialogMouseTool.polygon({
        strokeColor: '#FF33FF',
        strokeWeight: 2,
        strokeOpacity: 0.9,
        fillColor: '#1791fc',
        fillOpacity: 0.3
      });
      this.$message.success('请在地图上绘制巡区范围');
    },
    
    // 清除绘制
    clearDraw() {
      if (this.currentOverlay) {
        this.dialogMap.remove(this.currentOverlay);
        this.currentOverlay = null;
      }
      if (this.dialogMouseTool) {
        this.dialogMouseTool.close();
      }
    },
    
    // 完成绘制
    finishDraw() {
      if (!this.currentOverlay) {
        this.$message.warning('请先绘制巡区范围');
        return;
      }
      
      const path = this.currentOverlay.getPath();
      if (path && path.length >= 3) {
        this.form.area = path.map(point => [point.lng, point.lat]);
        this.$message.success('巡区范围绘制完成');
      } else {
        this.$message.error('巡区范围数据无效');
      }
    },
    // 表单提交
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 检查是否绘制了巡区范围
          if (!this.form.area || this.form.area.length === 0) {
            this.$message.error('请先绘制巡区范围');
            return;
          }
          
          // 使用数据转换工具确保数据类型正确
          const submitData = this.convertFormData(this.form);
          
          if (this.form.areaId) {
            updatePatrolArea(submitData).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addPatrolArea(submitData).then(response => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        areaId: undefined,
        areaName: undefined,
        areaType: 1,
        hasFence: 0, // 使用整数类型
        area: [],
        deptId: undefined
      };
      if (this.currentOverlay) {
        this.currentOverlay.setMap(null);
        this.currentOverlay = null;
      }
      // 清理弹窗地图
      if (this.dialogMap) {
        this.dialogMap.destroy();
        this.dialogMap = null;
      }
      if (this.dialogMouseTool) {
        this.dialogMouseTool = null;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        areaName: undefined,
        areaType: undefined
      };
      this.deptName = '';
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.areaId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加巡区';
      console.log('弹窗打开，开始初始化地图...');
      
      // 延迟初始化地图，确保弹窗完全打开
      setTimeout(() => {
        console.log('开始初始化弹窗地图...');
        this.initDialogMap().then(() => {
          console.log('地图初始化成功，开始重绘...');
          // 地图初始化成功后重绘
          this.resizeDialogMap();
        }).catch(err => {
          console.error('地图初始化失败:', err);
          this.$message.error('地图初始化失败，请刷新页面重试');
        });
      }, 800); // 增加到800ms
    },
    /** 跳转到绘图页面 */
    handleDraw() {
      this.$router.push('/patrol/area/draw');
    },
    /** 修改按钮操作 */
    handleModify(row) {
      const areaId = row.areaId || row.id;
      this.$router.push({
        path: '/patrol/area/draw',
        query: { areaId: areaId }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const areaIds = row.areaId || row.id || this.ids;
      const areaNames = row.areaName || this.ids.map(id => {
        const area = this.areaList.find(item => item.areaId === id);
        return area ? area.areaName : id;
      }).join(',');
      
      this.$modal.confirm('是否确认删除巡区名称为"' + areaNames + '"的数据项?').then(() => {
        return delPatrolArea(areaIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {});
    },
    /** 预览巡区 */
    handlePreview(row) {
      if (!this.map) {
        this.$message.warning('地图未初始化完成，请稍后再试');
        return;
      }
      
      // 清除当前显示的其他巡区
      this.map.clearMap();
      
      if (row.area && row.area.length > 0) {
        // 确保area是数组格式
        let path = row.area;
        if (typeof row.area === 'string') {
          try {
            path = JSON.parse(row.area);
          } catch (e) {
            this.$message.error('巡区坐标数据格式错误');
            console.error('巡区坐标数据格式错误:', row.area);
            return;
          }
        }
        
        // 验证坐标数据
        if (!this.validateCoordinates(path)) {
          this.$message.warning('巡区坐标数据无效，无法显示');
          return;
        }
        
        // 创建巡区多边形
        const polygon = new AMap.Polygon({
          path: path,
          strokeColor: '#FF33FF',
          strokeWeight: 3,
          strokeOpacity: 0.9,
          fillColor: '#1791fc',
          fillOpacity: 0.4,
          extData: row
        });
        
        // 添加到地图
        this.map.add(polygon);
        
        // 调整视图以显示整个巡区
        this.map.setFitView([polygon]);
        
        // 显示巡区信息
        this.$message.success(`正在查看巡区：${row.areaName}`);
      } else {
        this.$message.warning('该巡区没有设置范围数据');
      }
    },
    /** 分页大小改变 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    /** 当前页改变 */
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    
    /** 调试方法：检查巡区数据 */
    debugAreaData() {
      console.log('当前巡区列表数据:', this.areaList);
      this.areaList.forEach((area, index) => {
        console.log(`巡区${index + 1}:`, {
          name: area.areaName,
          area: area.area,
          areaType: typeof area.area,
          length: area.area ? area.area.length : 0
        });
      });
    },
    
    /** 数据转换工具：确保数据类型正确 */
    convertFormData(formData) {
      return {
        ...formData,
        hasFence: formData.hasFence ? 1 : 0,
        areaType: parseInt(formData.areaType) || 1,
        deptId: formData.deptId ? parseInt(formData.deptId) : null,
        areaId: formData.areaId ? parseInt(formData.areaId) : null,
        // 将坐标数组转换为JSON字符串
        area: Array.isArray(formData.area) ? JSON.stringify(formData.area) : formData.area
      };
    },
    // 验证坐标数据
    validateCoordinates(coordinates) {
      if (!Array.isArray(coordinates)) {
        return false;
      }
      
      for (let coord of coordinates) {
        if (!Array.isArray(coord) || coord.length < 2) {
          return false;
        }
        
        const [lng, lat] = coord;
        if (isNaN(lng) || isNaN(lat) || 
            lng < -180 || lng > 180 || 
            lat < -90 || lat > 90) {
          return false;
        }
      }
      
      return coordinates.length >= 3;
    },
    
    // 重绘弹窗地图
    resizeDialogMap() {
      if (this.dialogMap) {
        setTimeout(() => {
          this.dialogMap.resize();
          console.log('地图重绘完成');
        }, 100);
      }
    },
    
    // 强制初始化地图
    forceInitMap() {
      console.log('强制初始化地图...');
      if (this.dialogMap) {
        this.dialogMap.destroy();
        this.dialogMap = null;
      }
      if (this.dialogMouseTool) {
        this.dialogMouseTool = null;
      }
      
      setTimeout(() => {
        this.initDialogMap().then(() => {
          this.resizeDialogMap();
          this.$message.success('地图初始化成功');
        }).catch(err => {
          console.error('强制初始化失败:', err);
          this.$message.error('地图初始化失败');
        });
      }, 200);
    },
    // 部门节点点击
    handleNodeClick(node) {
      this.queryParams.deptId = node.id;
      this.getList();
    },
    // 过滤部门树
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 分配用户按钮操作 */
    handleAssignUsers(row) {
      this.currentArea = row;
      this.assignDialogVisible = true;
      this.loadAssignedUsers(row.areaId);
    },
    
    /** 加载已分配用户 */
    loadAssignedUsers(areaId) {
      this.assignLoading = true;
      getUsersByAreaId(areaId).then(response => {
        this.assignedUsers = response.data || [];
        this.assignLoading = false;
      }).catch(() => {
        this.assignLoading = false;
      });
    },
    
    /** 打开用户选择器 */
    openSelectUser() {
      this.$refs.selectUser.show();
    },
    
    /** 处理用户选择 */
    handleUserSelect(userIds) {
      if (userIds && userIds.length > 0) {
        // 获取选中用户的姓名信息
        const selectedUsers = this.$refs.selectUser.userList.filter(user => 
          userIds.includes(user.userId)
        );
        const userNames = selectedUsers.map(user => user.nickName || user.userName);
        
        // 默认分配为主要负责人
        batchAssignUsers(this.currentArea.areaId, userIds, userNames, 1).then(response => {
          this.$modal.msgSuccess('用户分配成功');
          this.loadAssignedUsers(this.currentArea.areaId);
        }).catch(() => {
          this.$modal.msgError('用户分配失败');
        });
      }
    },
    
    /** 移除用户分配 */
    removeAssign(row) {
      this.$modal.confirm('确认移除用户"' + (row.nickName || row.userName) + '"的巡区分配吗？').then(() => {
        return cancelUserAssign(this.currentArea.areaId, row.userId);
      }).then(() => {
        this.$modal.msgSuccess('移除成功');
        this.loadAssignedUsers(this.currentArea.areaId);
      }).catch(() => {});
    },
    
    /** 批量移除用户分配 */
    batchRemoveAssign() {
      if (this.selectedAssignIds.length === 0) {
        this.$modal.msgError('请选择要移除的用户');
        return;
      }
      
      this.$modal.confirm('确认移除选中的用户分配吗？').then(() => {
        const promises = this.selectedAssignIds.map(id => {
          const user = this.assignedUsers.find(u => u.id === id);
          return cancelUserAssign(this.currentArea.areaId, user.userId);
        });
        return Promise.all(promises);
      }).then(() => {
        this.$modal.msgSuccess('批量移除成功');
        this.loadAssignedUsers(this.currentArea.areaId);
        this.selectedAssignIds = [];
      }).catch(() => {});
    },
    
    /** 用户分配表格选择变化 */
    handleAssignSelectionChange(selection) {
      this.selectedAssignIds = selection.map(item => item.id);
    },
    /** 跳转到用户分配管理页面 */
    handleAssignManage() {
      this.$router.push('/patrol/area/assign');
    },
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  .head-container {
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    margin-bottom: 10px;
  }
  
  .map-container {
    height: 600px;
    width: 100%;
    border-radius: 4px;
    overflow: hidden;
  }

  .dialog-map-container {
    height: 500px;
    width: 100%;
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid #dcdfe6;
    position: relative;
    min-height: 500px;
    min-width: 300px;
  }

  .map-controls {
    margin-bottom: 10px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }
  
  /* 弹窗样式 */
  :deep(.el-dialog) {
    max-height: 90vh;
    overflow-y: auto;
  }
  
  :deep(.el-dialog__body) {
    max-height: calc(90vh - 120px);
    overflow-y: auto;
    padding: 20px;
  }

  /* 用户分配样式 */
  .assign-container {
    .assign-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #ebeef5;
      
      h4 {
        margin: 0;
        color: #303133;
      }
      
      .assign-actions {
        display: flex;
        gap: 10px;
      }
    }
  }
}
</style> 